package com.ilink.yanchuangservice.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ilink.ilinkapi.dto.ground.yanchuang.CommentRequest;
import com.ilink.ilinkapi.dto.ground.yanchuang.ProjectMetadataDTO;
import com.ilink.ilinkapi.dto.ground.yanchuang.YanchuangFilterRequest;
import com.ilink.ilinkapi.dto.ground.yanchuang.YanchuangWordCloudDataDTO;
import com.ilink.ilinkcommon.domain.R;
import com.ilink.ilinkcommon.log.method.MethodLog;
import com.ilink.yanchuangservice.entity.PO.YanchuangExhibitionTime;
import com.ilink.yanchuangservice.entity.VO.ProjectDetailResponse;
import com.ilink.yanchuangservice.entity.VO.ProjectSummaryResponse;
import com.ilink.yanchuangservice.mapper.YanchuangWordCloudDataMapper;
import com.ilink.yanchuangservice.service.YanchuangService;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.ilink.yanchuangservice.entity.PO.YanchuangWordCloudData;

@Slf4j
@RestController
@RequestMapping("/yanchuang")
@RequiredArgsConstructor
public class YanchuangController {

    private final YanchuangService yanchuangService;
    private final YanchuangWordCloudDataMapper yanchuangWordCloudDataMapper;


    /**
     * 保存项目数据
     * @param projectMetadataDTO 项目数据DTO
     * @return 保存结果
     */
    @MethodLog(value = "上传研创数据")
    @PostMapping("/save")
    public R saveProject(@RequestBody ProjectMetadataDTO projectMetadataDTO) {
        try {
            yanchuangService.saveProject(projectMetadataDTO);
            return R.ok("项目保存成功！");
        } catch (Exception e) {
            log.error("保存项目失败：{}", e.getMessage());
            return R.error("项目保存失败：" + e.getMessage());
        }
    }

    /**
     * 根据筛选条件分页返回项目列表
     * @param filterRequest 筛选条件请求对象
     * @return 项目分页列表
     */
    @MethodLog(value = "分页查询研创项目列表")
    @GetMapping("/list")
    public R listProjects(YanchuangFilterRequest filterRequest) {
        try {
            IPage<ProjectSummaryResponse> projectPage = yanchuangService.getProjectsByCondition(
                filterRequest.getKeywords(),
                filterRequest.getTag(),
                filterRequest.getPage(),
                filterRequest.getSize()
            );
            return R.ok("项目列表查询成功", projectPage);
        } catch (Exception e) {
            log.error("查询项目列表失败：{}", e.getMessage());
            return R.error("项目列表查询失败：" + e.getMessage());
        }
    }

    /**
     * 根据项目ID返回项目详情
     * @param id 项目ID
     * @return 项目详情
     */
    @MethodLog(value = "查询研创项目详情")
    @GetMapping("/detail/{id}")
    public R getProjectDetail(@PathVariable Long id) {
        try {
            ProjectDetailResponse response = yanchuangService.getProjectDetail(id);
            return response != null ? R.ok("项目详情查询成功", response) : R.error("未查询到对应的项目详情");
        } catch (Exception e) {
            log.error("查询项目详情失败：{}", e.getMessage());
            return R.error("项目详情查询失败：" + e.getMessage());
        }
    }

    /**
     * 提交项目评论
     * @param commentRequest 评论请求对象
     * @return 提交结果
     */
    @MethodLog(value = "提交项目评论")
    @PostMapping("/comment")
    public R submitComment(@RequestBody CommentRequest commentRequest) {
        try {
            yanchuangService.submitComment(
                commentRequest.getProjectId(),
                commentRequest.getContactInformation(),
                commentRequest.getComment()
            );
            return R.ok("评论提交成功！");
        } catch (Exception e) {
            log.error("提交评论失败：{}", e.getMessage());
            return R.error("评论提交失败：" + e.getMessage());
        }
    }


    /**
     * 更新所有展览的当前状态并返回展览列表
     */
    @MethodLog(value = "更新所有展览的当前状态并返回展览列表")
    @GetMapping("/exhibition_status")
    public R updateExhibitionStatus() {
        try {
            List<YanchuangExhibitionTime> exhibitionList = yanchuangService.updateExhibitionStatus();
            return R.ok("展览状态更新成功", exhibitionList);
        } catch (Exception e) {
            log.error("展览状态更新失败：{}", e.getMessage());
            return R.error("展览状态更新失败：" + e.getMessage());
        }
    }





    @MethodLog(value = "研创数据大屏返回词云数据")
    @PostMapping("/word_cloud")
    public ResponseEntity<Map<String, Object>> getWordCloud() {
        try {
            // 从数据库读取词云数据
            List<YanchuangWordCloudData> dataList = yanchuangWordCloudDataMapper.getWordCloudData();

            // 将 YanchuangWordCloudData 转换为 YanchuangWordCloudDataDTO
            List<YanchuangWordCloudDataDTO> dtoList = dataList.stream().map(data -> {
                YanchuangWordCloudDataDTO dto = new YanchuangWordCloudDataDTO();
                dto.setName(data.getName());
                dto.setValue(data.getValue());
                dto.setUrl(data.getUrl());
                return dto;
            }).collect(Collectors.toList());

            // 构建返回体
            Map<String, Object> responseBody = new HashMap<>();
            responseBody.put("status", 0);  // 自定义状态码
            responseBody.put("hitSugarSelf", true);
            responseBody.put("msg", "");
            responseBody.put("data", dtoList);

            return ResponseEntity.ok(responseBody);  // 返回 200 状态码

        } catch (Exception e) {
            log.error("获取词云数据失败：{}", e.getMessage());

            // 构建错误返回体
            Map<String, Object> errorBody = new HashMap<>();
            errorBody.put("status", 500);  // 自定义错误状态码
            errorBody.put("hitSugarSelf", false);
            errorBody.put("msg", "获取词云数据失败：" + e.getMessage());
            errorBody.put("data", Collections.emptyList());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorBody);
        }
    }



//    @GetMapping("/get_url")
//    public R getYanchuangUrl(@RequestParam String filename) {
//        try {
//            String fileWithoutExtension = filename.substring(0, filename.lastIndexOf('.'));
//            return R.ok(null, ossService.getStudyTreeResourceUrl("dataset-square-migrate", "yanchuang/" + fileWithoutExtension));
//        } catch (Exception e) {
//            return R.error("获取资源图片URL时发生错误：" + e.getMessage());
//        }
//    }
}
